<template>
    <div id="root">
        <div class="todo-container">
            <div class="todo-wrap">
                <Header :addTodo="addTodo"/>
                <List :todos="todos" :delTodo="deleteTodo" :updateTodo="updateTodo"/>
                <Footer :todos="state.todos" :isAllChecked="isAllChecked" :clearCompltedData="clearCompltedData"/>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts" name="App">
import Header from "@/components/Header.vue";
import Footer from "@/components/Footer.vue";
import List from "@/components/List.vue";
import {onMounted, reactive, toRefs, watch} from "vue";
import {type Todo} from "@/Types/Todo";
import {getData, saveData} from "@/components/localStorge";
// 定义数据
const state = reactive<{ todos: Todo[] }>({
    todos: []
})
const {todos} = toRefs(state)
onMounted(()=> {
    setTimeout(()=> {
        state.todos = getData()
    },1000)
})
// 添加数据
function addTodo(todo: Todo) {
    state.todos.unshift(todo)
}

// 删除数据
function deleteTodo(val) {
    state.todos = state.todos.filter(item => val !== item.id)
}

// 修改状态
function updateTodo(todo: Todo, isComplete: boolean) {
    todo.isCompleted = isComplete
}

// 全选，全不选
function isAllChecked(isCheckAll: boolean) {
    state.todos.forEach(item => {
        item.isCompleted = isCheckAll
    })
}

// 清楚已完成
function clearCompltedData() {
    state.todos = state.todos.filter(item => !item.isCompleted)
}

// 监听数据变化
watch(() => state.todos, (val) => {
    saveData(val)
}, {deep: true})
</script>

<style>
/*app*/
.todo-container {
    width: 600px;
    margin: 0 auto;
}

.todo-container .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
}

</style>
